<template>
  <div class="admin-page admin-mission-students">
    <div class="page-header">
      <h1>教学任务学员管理</h1>
      <p class="page-description">管理教学任务的学员信息，支持从队次批量导入或选择单个学员</p>
    </div>
    
    <!-- 教学任务列表组件 -->
    <MissionStudentTaskList
      :missions="filteredMissions"
      :loading="missionsLoading"
      :term-options="termOptions"
      :course-options="courseOptions"
      :selected-mission-id="selectedMissionId"
      :total-missions="totalMissions"
      :current-page="missionCurrentPage"
      :page-size="missionPageSize"
      v-model:term-filter="termFilter"
      v-model:course-filter="courseFilter"
      v-model:search-query="missionSearchQuery"
      @mission-select="handleMissionSelect"
      @page-change="handleMissionPageChange"
      @search-change="filterMissions"
      @filter-change="filterMissions"
      @term-change="onTermChange"
    />
    
    <!-- 学员管理区域 -->
    <div v-if="selectedMissionId" class="content-container">
      <!-- 选中的教学任务信息组件 -->
      <MissionStudentTaskInfo :mission="selectedMission" />
      
      <!-- 学员列表组件 -->
      <MissionStudentList
        :students="filteredStudents"
        :loading="loading"
        :total-students="totalStudents"
        :current-page="currentPage"
        :page-size="pageSize"
        v-model:search-query="searchQuery"
        @search-change="filterStudents"
        @import-students="openStudentImportDialog"
        @export-students="exportStudents"
        @clear-students="clearStudents"
        @remove-student="removeStudent"
        @page-change="handlePageChange"
      />
    </div>
    
    <!-- 未选择教学任务时的提示 -->
    <el-empty 
      v-else 
      description="请先选择教学任务"
      :image-size="200">
    </el-empty>
    
    <!-- 学员导入对话框 -->
    <StudentImportDialog
      v-if="selectedMission"
      v-model="studentImportDialogVisible"
      :teaching-mission="selectedMission"
      @imported="onStudentsImported"
    />
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { studentApi } from '@/api/student'
import { teachingMissionApi } from '@/api/teaching-mission'
import { termApi, courseApi } from '@/api/base-data'
import StudentImportDialog from '@/components/teaching-mission/dialogs/StudentImportDialog.vue'
import MissionStudentTaskList from '@/components/teaching-mission/forms/MissionStudentTaskList.vue'
import MissionStudentTaskInfo from '@/components/teaching-mission/forms/MissionStudentTaskInfo.vue'
import MissionStudentList from '@/components/teaching-mission/tables/MissionStudentList.vue'

export default {
  components: {
    StudentImportDialog,
    MissionStudentTaskList,
    MissionStudentTaskInfo,
    MissionStudentList
  },
  setup() {
    // 教学任务相关
    const teachingMissions = ref([])
    const filteredMissions = ref([])
    const selectedMissionId = ref(null)
    const selectedMission = ref(null)
    const missionsLoading = ref(false)
    const missionSearchQuery = ref('')
    const termFilter = ref('')
    const courseFilter = ref('')
    const termOptions = ref([])
    const courseOptions = ref([])
    
    // 教学任务分页相关
    const missionCurrentPage = ref(1)
    const missionPageSize = ref(10)
    
    // 学员列表相关
    const students = ref([])
    const filteredStudents = ref([])
    const searchQuery = ref('')
    const loading = ref(false)
    
    // 学员分页相关
    const currentPage = ref(1)
    const pageSize = ref(10)
    
    // 学员导入对话框
    const studentImportDialogVisible = ref(false)
    
    // 获取教学任务列表
    const fetchTeachingMissions = async () => {
      missionsLoading.value = true
      try {
        const res = await teachingMissionApi.getAllTeachingMissionsList()
        teachingMissions.value = res || []
        
        // 处理教师名称，将数组转换为字符串
        teachingMissions.value.forEach(mission => {
          if (mission.teacherNames && mission.teacherNames.length > 0) {
            mission.teacherName = mission.teacherNames.join(', ')
          } else {
            mission.teacherName = '未分配'
          }
          
          // 学员数量已经在后端计算并返回，无需前端再次获取
          // mission.studentCount 字段已包含正确的学员数量
        })
        
        // 提取所有学期选项
        const termSet = new Set()
        teachingMissions.value.forEach(mission => {
          if (mission.termName) {
            termSet.add(mission.termName)
          }
        })
        termOptions.value = Array.from(termSet).map(term => ({
          label: term,
          value: term
        }))
        
        // 提取所有课程选项
        const courseSet = new Set()
        teachingMissions.value.forEach(mission => {
          if (mission.courseName) {
            courseSet.add(mission.courseName)
          }
        })
        courseOptions.value = Array.from(courseSet).map(course => ({
          label: course,
          value: course
        }))
        
        // 初始化筛选后的任务
        filterMissions()
        missionsLoading.value = false
      } catch (error) {
        console.error('获取教学任务列表失败:', error)
        ElMessage.error('获取教学任务列表失败')
        missionsLoading.value = false
      }
    }
    
    // 过滤教学任务
    const filterMissions = () => {
      // 如果没有选择学期，返回空数组
      if (!termFilter.value) {
        filteredMissions.value = []
        return
      }
      
      let filtered = teachingMissions.value
      
      // 必须匹配学期
      filtered = filtered.filter(mission => 
        mission.termName === termFilter.value
      )
      
      // 根据搜索关键词过滤
      if (missionSearchQuery.value) {
        const query = missionSearchQuery.value.toLowerCase()
        filtered = filtered.filter(mission => 
          (mission.courseName && mission.courseName.toLowerCase().includes(query)) ||
          (mission.courseCode && mission.courseCode.toLowerCase().includes(query)) ||
          (mission.teacherNames && mission.teacherNames.some(name => 
            name.toLowerCase().includes(query)
          ))
        )
      }
      
      // 根据课程过滤
      if (courseFilter.value) {
        filtered = filtered.filter(mission => 
          mission.courseName === courseFilter.value
        )
      }
      
      filteredMissions.value = filtered
      missionCurrentPage.value = 1 // 重置分页
    }
    
    // 计算总任务数
    const totalMissions = computed(() => 
      Array.isArray(filteredMissions.value) ? filteredMissions.value.length : 0
    )
    
    // 处理任务页码变化
    const handleMissionPageChange = (page) => {
      missionCurrentPage.value = page
    }
    
    // 选择教学任务
    const handleMissionSelect = (mission) => {
      selectedMissionId.value = mission.id
      selectedMission.value = mission
      fetchStudentsByMission(mission.id)
    }
    
    // 获取学员列表（根据教学任务ID）
    const fetchStudentsByMission = async (missionId) => {
      if (!missionId) return
      
      loading.value = true
      try {
        const res = await teachingMissionApi.getTeachingMissionStudents(missionId)
        students.value = res || []
        filteredStudents.value = [...students.value]
        loading.value = false
      } catch (error) {
        console.error(`获取教学任务(ID=${missionId})学员列表失败:`, error)
        ElMessage.error('获取学员列表失败')
        loading.value = false
      }
    }
    
    // 搜索过滤学员
    const filterStudents = () => {
      if (!searchQuery.value) {
        filteredStudents.value = [...students.value]
      } else {
        const query = searchQuery.value.toLowerCase()
        filteredStudents.value = students.value.filter(student => 
          (student.name && student.name.toLowerCase().includes(query)) ||
          (student.studentId && student.studentId.toLowerCase().includes(query)) ||
          (student.className && student.className.toLowerCase().includes(query)) ||
          (student.majorName && student.majorName.toLowerCase().includes(query))
        )
      }
      currentPage.value = 1 // 重置页码
    }
    
    // 计算总学员数
    const totalStudents = computed(() => 
      Array.isArray(filteredStudents.value) ? filteredStudents.value.length : 0
    )
    
    // 处理页码变化
    const handlePageChange = (page) => {
      currentPage.value = page
    }
    
    // 移除学员
    const removeStudent = (student) => {
      if (!selectedMissionId.value) return
      
      ElMessageBox.confirm(
        `确定要将学员 ${student.name} (${student.studentId}) 从该教学任务中移除吗？`,
        '移除确认',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(async () => {
        try {
          await teachingMissionApi.removeStudentFromTeachingMission(selectedMissionId.value, student.id)
          ElMessage.success('移除学员成功')
          fetchStudentsByMission(selectedMissionId.value)
          
          // 只更新教学任务列表中的学员数量（selectedMission.value 指向同一个对象，避免重复减少）
          const missionIndex = teachingMissions.value.findIndex(m => m.id === selectedMissionId.value)
          if (missionIndex !== -1) {
            teachingMissions.value[missionIndex].studentCount = 
              (teachingMissions.value[missionIndex].studentCount || 0) - 1
          }
        } catch (error) {
          console.error('移除学员失败:', error)
          ElMessage.error(`移除学员失败: ${error.message || '未知错误'}`)
        }
      }).catch(() => {
        // 取消移除，不做任何操作
      })
    }
    
    // 清空教学任务所有学员
    const clearStudents = () => {
      if (!selectedMissionId.value) return
      
      ElMessageBox.confirm(
        `确定要清空该教学任务的所有学员吗？此操作不可恢复！`,
        '清空确认',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          dangerouslyUseHTMLString: true
        }
      ).then(async () => {
        try {
          await teachingMissionApi.clearTeachingMissionStudents(selectedMissionId.value)
          ElMessage.success('清空学员成功')
          
          // 清空本地学员数据
          students.value = []
          filteredStudents.value = []
          
          // 更新教学任务列表中的学员数量
          const missionIndex = teachingMissions.value.findIndex(m => m.id === selectedMissionId.value)
          if (missionIndex !== -1) {
            teachingMissions.value[missionIndex].studentCount = 0
          }
        } catch (error) {
          console.error('清空学员失败:', error)
          ElMessage.error(`清空学员失败: ${error.message || '未知错误'}`)
        }
      }).catch(() => {
        // 取消清空，不做任何操作
      })
    }
    
    // 导出学员名单
    const exportStudents = () => {
      if (!selectedMissionId.value || !students.value.length) {
        ElMessage.warning('没有可导出的学员数据')
        return
      }
      
      // 准备CSV数据
      const headers = ['学号', '姓名', '队次', '专业']
      const csvContent = [
        headers.join(','),
        ...students.value.map(student => [
          student.studentId || '',
          student.name || '',
          student.className || '',
          student.majorName || ''
        ].join(','))
      ].join('\n')
      
      // 创建下载链接
      const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' })
      const url = URL.createObjectURL(blob)
      const link = document.createElement('a')
      link.href = url
      link.setAttribute('download', `${selectedMission.value.courseName || '教学任务'}-学员名单.csv`)
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      
      ElMessage.success('学员名单导出成功')
    }
    
    // 打开学员导入对话框
    const openStudentImportDialog = () => {
      if (!selectedMissionId.value) {
        ElMessage.warning('请先选择教学任务')
        return
      }
      
      studentImportDialogVisible.value = true
    }
    
    // 学员导入完成回调
    const onStudentsImported = (count) => {
      // 刷新学员列表
      fetchStudentsByMission(selectedMissionId.value)
      
      // 更新所选教学任务的学员数量
      if (selectedMission.value && count) {
        selectedMission.value.studentCount = (selectedMission.value.studentCount || 0) + count
      }
      
      // 更新教学任务列表中的学员数量
      if (count) {
        const missionIndex = teachingMissions.value.findIndex(m => m.id === selectedMissionId.value)
        if (missionIndex !== -1) {
          teachingMissions.value[missionIndex].studentCount = 
            (teachingMissions.value[missionIndex].studentCount || 0) + count
        }
      }
      
      // 显示成功消息
      ElMessage.success('学员导入成功')
    }
    
    // 学期变化处理
    const onTermChange = async () => {
      // 如果尝试清空学期，则重新设置为当前学期
      if (!termFilter.value) {
        try {
          const currentTerm = await termApi.getCurrentTerm()
          if (currentTerm && currentTerm.name) {
            termFilter.value = currentTerm.name
            ElMessage.warning('学期不能为空，已自动设置为当前学期')
          }
        } catch (error) {
          console.warn('获取当前学期失败:', error)
          ElMessage.error('学期不能为空')
        }
        return
      }
      
      courseFilter.value = '' // 重置课程过滤
      missionCurrentPage.value = 1 // 重置分页
      filterMissions()
    }
    
    // 获取当前学期
    const fetchCurrentTerm = async () => {
      try {
        const currentTerm = await termApi.getCurrentTerm()
        if (currentTerm && currentTerm.name) {
          termFilter.value = currentTerm.name
        }
      } catch (error) {
        console.warn('获取当前学期失败:', error)
        // 不显示错误消息，因为这不是关键功能
      }
    }
    
    // 页面初始化
    onMounted(async () => {
      await fetchTeachingMissions()
      await fetchCurrentTerm()
      filterMissions() // 应用默认学期过滤
    })
    
    return {
      // 教学任务相关
      teachingMissions,
      filteredMissions,
      selectedMissionId,
      selectedMission,
      missionsLoading,
      missionSearchQuery,
      termFilter,
      courseFilter,
      termOptions,
      courseOptions,
      totalMissions,
      missionCurrentPage,
      missionPageSize,
      
      // 学员列表相关
      students,
      filteredStudents,
      totalStudents,
      searchQuery,
      loading,
      currentPage,
      pageSize,
      
      // 学员导入对话框
      studentImportDialogVisible,
      
      // 方法
      filterMissions,
      onTermChange,
      handleMissionSelect,
      handleMissionPageChange,
      filterStudents,
      handlePageChange,
      removeStudent,
      clearStudents,
      openStudentImportDialog,
      onStudentsImported,
      exportStudents
    }
  }
}
</script>

<style scoped>
.admin-mission-students {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h1 {
  margin: 0 0 10px 0;
  font-size: 24px;
  color: #303133;
}

.page-header .page-description {
  margin: 0;
  color: #606266;
  font-size: 14px;
}

.content-container {
  margin-top: 20px;
}
</style>
